<?php
	use Zend\XmlRpc\Value\Integer;
require_once('include/db_connection.php');

	class PlayerHalfItHits {
		public $currentPlayerID;
		public $targets = array();
		public $multiplier = array();
	}
	if (isset($_GET['request']) && isset($_GET['game_id'])) {
		$gameID = $_GET['game_id'];
	}
	if (isset($_GET['request']) && isset($_GET['playerid'])) {
		$players = getCurrentPlayersSorted($gameID,$_GET['playerid']);
	}
	if (isset($_GET['request']) && isset($_GET['game_uuid'])) {
		$gameUUID = $_GET['game_uuid'];
	}
	if (isset($_GET['request']) && $_GET['request'] == 'undo') {
		undo($gameUUID);
		$gameGroup = getGameGroup($gameID);
		processGame($gameGroup,$gameID,$gameUUID,$players,null,null);
		exit;
	}
	if (isset($_GET['request']) && $_GET['request'] == 'livedartscoreboard') {
		$sql = "select max(game_uuid) gameUUID from game_score_v2";
		$gameUUID =  $mysqli->query($sql)->fetch_object()->gameUUID;

		$sql = "select distinct game_id gameID from game_score_v2 where game_uuid=".$gameUUID;
		$gameID =  $mysqli->query($sql)->fetch_object()->gameID;

		$sql = "select distinct player_id from game_score_v2 where game_uuid=".$gameUUID;
		$res = $mysqli->query($sql);
		$players = array();
		while (($row = $res->fetch_assoc()) != false) {
			array_push($players, $row['player_id']);
		}
		printDartScoreBoard($gameID,$gameUUID,$players);
		echo "<script type='text/javascript'>setTimeout(function(){window.location.reload(1);}, 10000);</script>";
		exit;
	}
	if (isset($_GET['request']) && $_GET['request'] == 'gamedetails2') {
		$gameUUID = $_GET['gameUUID'];

		$sql = "select distinct game_id gameID from game_score_v2 where game_uuid=".$gameUUID;
		$gameID =  $mysqli->query($sql)->fetch_object()->gameID;

		$sql = "select distinct player_id from game_score_v2 where game_uuid=".$gameUUID;
		$res = $mysqli->query($sql);
		$players = array();
		while (($row = $res->fetch_assoc()) != false) {
			array_push($players, $row['player_id']);
		}
		printDartScoreBoard($gameID,$gameUUID,$players);
		exit;
	}

	if (isset($_GET['request']) && $_GET['request'] == 'startdartboard') {
		if (!isset($_GET['playerid'])) {
			echo "Bitte Spieler ausw&auml;hlen!";
			exit;
		}
		if(getNewGameID($gameID) != 0) {
			$gameID = getNewGameID($gameID);
			$gameGroup = getGameGroup($gameID);
			$gameUUID = getNewGameUUID();
			printDartBoard($gameID,$gameUUID,$players);
			exit;
		} else {
			echo "Das Spiel kommt noch!";
			exit;
		}
	}
	else if (isset($_GET['request']) && $_GET['request'] == 'startdartscoreboard') {
		$gameUUID = getNewGameUUID();
		$gameName = getCurrentGameName($gameID);
		$gameGroup = getGameGroup($gameID);
		if($gameGroup == 'Half It') {
			$halfit = initHalfIt($players,$gameName);
			saveGameData($gameUUID,$halfit);
		} else if($gameGroup == 'Scream') {
			initScream($players,$gameName,$gameUUID);
		}

		printDartScoreBoard($gameID,$gameUUID,$players);
		exit;
	}
	// dartboard
	else if (isset($_GET['request']) && $_GET['request'] == 'dartboard') {
		session_start();
		$score = $_GET['score'];
		$scoreMultiplier = $_GET['score_multiplier'];
		$scoreSum = $score * $scoreMultiplier;
		$gameGroup = getGameGroup($gameID);
		processGame($gameGroup,$gameID,$gameUUID,$players,$score,$scoreMultiplier);
		exit;
	}
	// spreadDropouts
	else if (isset($_GET['request']) && $_GET['request'] == 'spreadDropouts') {
		session_start();
		$gameGroup = getGameGroup($gameID);
		$gameUUID = $_SESSION['gamesData']['gameUUID'];
		$plID = $_GET['players'];
		$currentRound = getCurrentRound($gameID,$gameUUID,$players);
		$currentPlayerID = getCurrentPlayer($gameID,$gameUUID,$currentRound,$players);

		spreadDropouts($plID,$gameID,$gameUUID,$currentPlayerID,$players);

		processEmpty($gameID,$_SESSION['gamesData']['gameUUID'],$players);
		exit;
	}
	// dartboard live view
	else if (isset($_GET['request']) && $_GET['request'] == 'dartboardliveview') {
		processGame($gameGroup,$gameID,$gameUUID,$players,$score,$scoreMultiplier);
		exit;
	}

	function processGame($gameGroup,$gameID,$gameUUID,$players,$score,$scoreMultiplier) {
		switch ($gameGroup) {
			case "Count Up":
				processScoreCountUp($gameID,$gameUUID,$score,$scoreMultiplier,$players);
				break;
			case "X01":
				processScoreX01($gameID,$gameUUID,$score,$scoreMultiplier,$players);
				break;
			case "Half It":
				processScoreHalfIt($gameID,$gameUUID,$score,$scoreMultiplier,$players);
				break;
			case "Scream":
				processScoreScream($gameID,$gameUUID,$score,$scoreMultiplier,$players);
				break;
		}
	}

	function saveGameData($gameUUID,$data) {
		global $mysqli;
		$jsonData = json_encode($data);
		$sql = "select max(game_uuid) maxid from games_data_v2";
		$maxID = $mysqli->query($sql)->fetch_object()->maxid;
		if ($maxID == $gameUUID) {
			$sql = "delete from games_data_v2 where game_uuid=$gameUUID";
			mysqli_query($mysqli, $sql);
			$mysqli->commit();
		}
		$sql = "insert into games_data_v2 (game_uuid,data) VALUES($gameUUID,'$jsonData')";
		mysqli_query($mysqli, $sql);
		$mysqli->commit();
	}
	function getGameData($gameUUID) {
		global $mysqli;
		$sql = "select data from games_data_v2 where game_uuid=".$gameUUID;
		$jsonData = json_decode($mysqli->query($sql)->fetch_object()->data);
		return $jsonData;
	}

	function undo($gameUUID) {
		session_start();
		global $mysqli;
		$id = $mysqli->query("select max(id) id from game_score_v2 where game_uuid = $gameUUID")->fetch_object()->id;
		mysqli_query($mysqli, "delete from game_score_v2 where id = $id");
		$mysqli->commit();

	}
	function getCurrentPlayersSorted($gameID,$players) {
		global $mysqli;
		$yearkw = date('Y') . ltrim( date('W'),'0');
		$res = $mysqli->query("select * from view_score_kw_winner where yearkw=" . $yearkw);
		$playersSorted = array();
		while (($row = $res->fetch_assoc()) != false) {
			if(in_array($row['player_id'],$players)) {
				array_push($playersSorted, $row['player_id']);
			}
		}
		if(count($playersSorted) == 0) {
			$res = $mysqli->query("select * from players, (select sum(score_abs)/count(*) score_abs,player_id from view_score_kw where score!=-1 group by player_id ) score where players.id = score.player_id order by score_abs desc");
			while (($row = $res->fetch_assoc()) != false) {
				if(in_array($row['player_id'],$players)) {
					array_push($playersSorted, $row['player_id']);
				}
			}
		}
		foreach($players as $plID) {
			if(!in_array($plID,$playersSorted)) {
				array_push($playersSorted, $plID);
			}
		}
		if(getGameGroup($gameID) == 'Scream') {
			return $playersSorted;
		} else {
			return array_reverse($playersSorted);
		}
	}
	function getGameGroup($gameID) {
		global $mysqli;
		$sql = "select gameGroup from games_v2 where id=".$gameID;
		if($mysqli->query($sql)->fetch_object() != null) {
			return $mysqli->query($sql)->fetch_object()->gameGroup;
		}
	}
	function getNewGameUUID() {
		global $mysqli;
		$sql = "select max(game_uuid) maxid from game_score_v2";
		$maxID = $mysqli->query($sql)->fetch_object()->maxid;
		if($maxID == null) $maxID = 1;
		return $maxID+1;
	}
	function processScoreCountUp($gameID,$gameUUID,$score,$scoreMultiplier,$players) {
		global $mysqli;

		$currentInCondition = getCurrentInCondition($gameID);
		$currentOutCondition = getCurrentOutCondition($gameID);
		$gameStartPoints = getGameStartPoints($gameID);
		$gameTargetPoints = getGameTargetPoints($gameID);
		$currentRound = getCurrentRound($gameID,$gameUUID,$players);
		$currentPlayerID = getCurrentPlayer($gameID,$gameUUID,$currentRound,$players);
		$dartsCount = getDartsRoundCount($gameUUID,$currentRound,$currentPlayerID);
		if ($dartsCount == 3) {
			$currentRound+=1;
			$dartsCount = 0;
		}

		// save score
		if ($score !=null && $scoreMultiplier != null) {
			$currentPlayerRestPoints = getCurrentPlayerRestPoints($gameID,$gameUUID,$currentPlayerID);
			$currentPlayerPoints = getCurrentPlayerPoints($gameID,$gameUUID,$currentPlayerID);
			if(getGameGroup($gameID) == 'Count Up') {
				if(getCurrentGameName($gameID) == '301 U&D') {
					if($currentRound % 2 != 0) {
						// up
						if($score == 0) {
							$score = 60;
							$scoreMultiplier = 1;
							insertScore($gameID,$gameUUID,-$score,$scoreMultiplier,$currentPlayerID,$currentRound,$dartsCount);
						} else {
							insertScore($gameID,$gameUUID,$score,$scoreMultiplier,$currentPlayerID,$currentRound,$dartsCount);
						}
					} else {
						// down
						if($score == 0) {
							$score = 60;
							$scoreMultiplier = 1;
						}
						insertScore($gameID,$gameUUID,-$score,$scoreMultiplier,$currentPlayerID,$currentRound,$dartsCount);
					}
				} else {
					insertScore($gameID,$gameUUID,$score,$scoreMultiplier,$currentPlayerID,$currentRound,$dartsCount);
				}
			}
		}

		$currentPlayerPoints = getCurrentPlayerPoints($gameID,$gameUUID,$currentPlayerID);

		$currentPlayerID = getCurrentPlayer($gameID,$gameUUID,$currentRound,$players);

		$dartsCount = getDartsRoundCount($gameUUID,$currentRound,$currentPlayerID);

		if ($dartsCount == 3) {
			$dartsCount=0;
		}

		printStatisticsX01($gameID,$gameUUID,$currentPlayerID,$players);

	}
	function processEmpty($gameID,$gameUUID,$players) {
		$currentRound = getCurrentRound($gameID,$gameUUID,$players);
		$currentPlayerID = getCurrentPlayer($gameID,$gameUUID,$currentRound,$players);
		printStatisticsX01($gameID,$gameUUID,$currentPlayerID,$players);
	}
	function processScoreScream($gameID,$gameUUID,$score,$scoreMultiplier,$players,$becauseDropping = 0) {
		global $mysqli;

		$currentInCondition = getCurrentInCondition($gameID);
		$currentOutCondition = getCurrentOutCondition($gameID);
		$gameStartPoints = getGameStartPoints($gameID);
		$gameTargetPoints = getGameTargetPoints($gameID);
		$currentRound = getCurrentRound($gameID,$gameUUID,$players);
		$currentPlayerID = getCurrentPlayer($gameID,$gameUUID,$currentRound,$players);
		$dartsCount = getDartsRoundCount($gameUUID,$currentRound,$currentPlayerID);
		if ($dartsCount == 3) {
			$currentRound+=1;
			$dartsCount = 0;
		}

		// save score
		if ($score !=null && $scoreMultiplier != null) {
			if(getGameGroup($gameID) == 'Scream') {
				$currentPlayerPoints = getCurrentPlayerPoints($gameID,$gameUUID,$currentPlayerID);
				$rest = $currentPlayerPoints + ($score * $scoreMultiplier);
				if($rest > $gameTargetPoints) {
					switch ($dartsCount) {
						case 0:
							$roundScore = getRoundScore($gameUUID,$currentRound,$currentPlayerID);
							insertScore($gameID,$gameUUID,-$roundScore,1,$currentPlayerID,$currentRound,0);
							insertScore($gameID,$gameUUID,0,0,$currentPlayerID,$currentRound,1);
							insertScore($gameID,$gameUUID,0,0,$currentPlayerID,$currentRound,2);
						break;
						case 1:
							$roundScore = getRoundScore($gameUUID,$currentRound,$currentPlayerID);
							insertScore($gameID,$gameUUID,-$roundScore,1,$currentPlayerID,$currentRound,1);
							insertScore($gameID,$gameUUID,0,0,$currentPlayerID,$currentRound,2);
						break;
						case 2:
							$roundScore = getRoundScore($gameUUID,$currentRound,$currentPlayerID);
							insertScore($gameID,$gameUUID,-$roundScore,1,$currentPlayerID,$currentRound,2);
						break;
					}
						$dartsCount = 3;
				} else {
					insertScore($gameID,$gameUUID,$score,$scoreMultiplier,$currentPlayerID,$currentRound,$dartsCount);
					$mysqli->commit();
				}
				$currentPlayerPoints = getCurrentPlayerPoints($gameID,$gameUUID,$currentPlayerID);

				foreach($players as $playerID) {
					if($playerID != $currentPlayerID && !checkPlayerWin($gameID,$gameUUID,$playerID,$currentRound)) {
						$restPlSub = getCurrentPlayerPoints($gameID,$gameUUID,$playerID);
						if ($currentPlayerPoints != 0 && $currentPlayerPoints == $restPlSub) {
							$_SESSION['playersData']['playerId_'.$playerID]['zero']++;
							$_SESSION['playersData']['playerId_'.$playerID]['lostCounts'] = $_SESSION['playersData']['playerId_'.$playerID]['lostCounts'] + $currentPlayerPoints;
							$sql = "select id,score,score_multiplier from game_score_v2 where player_id =".$playerID." order by id desc limit 1";
							$id = $mysqli->query($sql)->fetch_object()->id;
							$scorePlSub = $mysqli->query($sql)->fetch_object()->score;
							$scoreMultiplierPlSub = $mysqli->query($sql)->fetch_object()->score_multiplier;
							$sql = "update game_score_v2 set score=".intval(-$restPlSub+$scorePlSub*$scoreMultiplierPlSub).",score_multiplier=1 where id=".$id;
							mysqli_query($mysqli, $sql);
							$mysqli->commit();
						}
					}
					if($playerID == $currentPlayerID) {
						collectDropouts($currentPlayerID,$gameID,$gameUUID,$currentRound);
					}
				}
				resetDropouts($currentPlayerID,$players,$gameID,$gameUUID,$currentRound,$becauseDropping);
			}
		}

		$currentPlayerID = getCurrentPlayer($gameID,$gameUUID,$currentRound,$players);

		handleDropouts($gameID,$gameUUID,$currentPlayerID,$players);

		$dartsCount = getDartsRoundCount($gameUUID,$currentRound,$currentPlayerID);

		if ($dartsCount == 3) {
			$dartsCount=0;
		}

		printStatisticsX01($gameID,$gameUUID,$currentPlayerID,$players);
	}
	function processScoreX01($gameID,$gameUUID,$score,$scoreMultiplier,$players) {
		global $mysqli;

		$currentInCondition = getCurrentInCondition($gameID);
		$currentOutCondition = getCurrentOutCondition($gameID);
		$gameStartPoints = getGameStartPoints($gameID);
		$gameTargetPoints = getGameTargetPoints($gameID);
		$currentRound = getCurrentRound($gameID,$gameUUID,$players);

		$currentPlayerID = getCurrentPlayer($gameID,$gameUUID,$currentRound,$players);

		$dartsCount = getDartsRoundCount($gameUUID,$currentRound,$currentPlayerID);
		if ($dartsCount == 3) {
			$currentRound+=1;
			$dartsCount = 0;
		}

		// save score
		if ($score !=null && $scoreMultiplier != null) {
			$currentPlayerRestPoints = getCurrentPlayerRestPoints($gameID,$gameUUID,$currentPlayerID);
			if(getGameGroup($gameID) == 'Count Up') {
				insertScore($gameID,$gameUUID,$score,$scoreMultiplier,$currentPlayerID,$currentRound,$dartsCount);
			} else if(getGameGroup($gameID) == 'X01') {
				$rest = $currentPlayerRestPoints - ($score * $scoreMultiplier);
				// in
				if($currentPlayerRestPoints == $gameStartPoints && (($currentInCondition == 'DI' && $scoreMultiplier != 2) || ($currentInCondition == 'MI' && $scoreMultiplier != 2 && $scoreMultiplier != 3))){
					insertScore($gameID,$gameUUID,0,0,$currentPlayerID,$currentRound,$dartsCount);
				}
				// out
				else  if(      ($rest < 0)
						    || ($currentOutCondition == 'DO' && $scoreMultiplier == 2 && $rest < 2 && $rest != 0)
						    || ($currentOutCondition == 'DO' && $scoreMultiplier != 2 && ($rest == 0 || $rest < 2))
						    || ($currentOutCondition == 'MO' && ($scoreMultiplier == 2 || $scoreMultiplier == 3) && $rest < 2 && $rest != 0)
							|| ($currentOutCondition == 'MO' && ($scoreMultiplier != 2 || $scoreMultiplier != 3) && ($rest == 0 || $rest < 2))
						) {
					if($dartsCount==0) {
						$roundScore = getRoundScore($gameUUID,$currentRound,$currentPlayerID);
						insertScore($gameID,$gameUUID,-$roundScore,1,$currentPlayerID,$currentRound,0);
						insertScore($gameID,$gameUUID,0,0,$currentPlayerID,$currentRound,1);
						insertScore($gameID,$gameUUID,0,0,$currentPlayerID,$currentRound,2);
					}
					if($dartsCount==1) {
						$roundScore = getRoundScore($gameUUID,$currentRound,$currentPlayerID);
						insertScore($gameID,$gameUUID,-$roundScore,1,$currentPlayerID,$currentRound,1);
						insertScore($gameID,$gameUUID,0,0,$currentPlayerID,$currentRound,2);
					}
					if($dartsCount==2) {
						$roundScore = getRoundScore($gameUUID,$currentRound,$currentPlayerID);
						insertScore($gameID,$gameUUID,-$roundScore,1,$currentPlayerID,$currentRound,2);
					}
					$dartsCount = 3;
				} else {
					insertScore($gameID,$gameUUID,$score,$scoreMultiplier,$currentPlayerID,$currentRound,$dartsCount);
				}
			}
		}

		$currentPlayerPoints = getCurrentPlayerPoints($gameID,$gameUUID,$currentPlayerID);

		$currentPlayerID = getCurrentPlayer($gameID,$gameUUID,$currentRound,$players);

		$dartsCount = getDartsRoundCount($gameUUID,$currentRound,$currentPlayerID);

		if ($dartsCount == 3) {
			$dartsCount=0;
		}

		printStatisticsX01($gameID,$gameUUID,$currentPlayerID,$players);

	}
	function initHalfIt($players,$gameName) {
		$halfit = array();

		if($gameName == 'Crazy') {
			foreach($players as $plID) {
				$playerHalfItHits = new PlayerHalfItHits();
				$playerHalfItHits->playerID = $plID;

				$numbers = range(11, 20);
				$rands = array();
				for ($i=0; $i < 10; $i++) {
				  $ok = false;
				  while (!$ok) {
					$x = array_rand($numbers);
					$ok = !in_array($numbers[$x], $rands) && $numbers[$x] != $i;
				  }
				  $rands[$i] = $numbers[$x];
				  unset($numbers[$x]);
				}
				$playerHalfItHits->targets = $rands;

				$multiplier = array();
				for($i=0;$i<10;$i++) {
					array_push($multiplier,rand(1,3));
				}
				$playerHalfItHits->multiplier = $multiplier;
				array_push($halfit,$playerHalfItHits);
			}
			return $halfit;
		} else if($gameName == '10') {
			$numbers = range(11, 20);
			$rands = array();
			for ($i=0; $i < 10; $i++) {
			  $ok = false;
			  while (!$ok) {
				$x = array_rand($numbers);
				$ok = !in_array($numbers[$x], $rands) && $numbers[$x] != $i;
			  }
			  $rands[$i] = $numbers[$x];
			  unset($numbers[$x]);
			}
			array_push($rands,25);
			foreach($players as $plID) {
				$playerHalfItHits = new PlayerHalfItHits();
				$playerHalfItHits->playerID = $plID;
				$playerHalfItHits->targets = $rands;

				$multiplier = array(1,1,1,2,1,1,1,1,3,1,1);
				$playerHalfItHits->multiplier = $multiplier;
				array_push($halfit,$playerHalfItHits);
			}
			return $halfit;
		}
	}

	/**
	 * Initial filling of the Session-Array.
	 * @access public
	 *
	 * @param array $players
	 * @param integer $gameName
	 * @param integer $gameUUID
	 * @return
	 * @author Harlecino
	 */
	function initScream($players,$gameName,$gameUUID) {
		session_start();
		$_SESSION['gamesData']['gameUUID'] = $gameUUID;
		foreach($players as $plID) {
			$newArray = array(
					"playerId" => $plID,			// Unique ID of the player
					"zero" => '0',					// Wie oft einer genullt wurde
					"lostCounts" => '0',			// Wie viele Punkte er durch die Nullerei verloren hat
					"dropoutsAvailable" => '0',		// Wie viele Aussetzer der Spieler noch vergeben kann
					"dropoutsReceivedInUse" => '0',	// Wie viele Aussetzer der Spieler noch aussetzen muss
					"dropoutsReceivedTotal" => '0'	// Wie viele Aussetzer der Spieler insgesamt hatte
			);
			$_SESSION['playersData']['playerId_'.$plID] = $newArray;
		}
	}

	/**
	 * Logic to collect the dropouts for deal out to the other player.
	 * @access public
	 * @param integer $plID
	 * @param integer $gameID
	 * @param integer $gameUUID
	 * @return integer
	 * @author Harlecino
	 */
	function collectDropouts($plID,$gameID,$gameUUID) {
		global $mysqli;
		$sql = "select id,score,score_multiplier from game_score_v2 where player_id =".$plID." order by id desc limit 1";
		$scorePlSub = $mysqli->query($sql)->fetch_object()->score;
		$scoreMultiplierPlSub = $mysqli->query($sql)->fetch_object()->score_multiplier;
		$currentPlayerPoints = $scoreMultiplierPlSub*$scorePlSub;

		if (getCurrentPlayerRestPoints($gameID,$gameUUID,$plID) == 111 || getCurrentPlayerRestPoints($gameID,$gameUUID,$plID) == 222) {
			$_SESSION['playersData']['playerId_'.$plID]['dropoutsAvailable']++;
		}
		if ($currentPlayerPoints == "50") {
			$_SESSION['playersData']['playerId_'.$plID]['dropoutsAvailable']++;
		}
		return $_SESSION['playersData']['playerId_'.$plID]['dropoutsAvailable'];
	}

	/**
	 * Provides the button for the victims to dropout.
	 * @access public
	 * @param integer $plID
	 * @param array $players
	 * @param integer $gameID
	 * @param integer $gameUUID
	 * @return string
	 * @author Harlecino
	 */
	function offerDropouts($plID,$players,$gameID,$gameUUID) {
		$dropoutsAvailable = NULL;

		foreach($players as $player) {
			if($_SESSION['playersData']['playerId_'.$player]['dropoutsAvailable'] > 0) {
				$dropoutsAvailable = true;
				$dropoutPlayer = $player;
			}
		}
		if(isset($dropoutsAvailable) && ($plID != $dropoutPlayer)) {
			echo "<br /><span class='dropout' data-gameid='".$gameID."' data-playerid='".$plID."' onclick='writeForDrops(this)'>Aussetzen!</span>";
		}
	}

	/**
	 * Provides the button for a rundom dropout.
	 * @access public
	 * @param integer $plID
	 * @param array $players
	 * @param integer $gameID
	 * @param integer $gameUUID
	 * @return string
	 * @author Harlecino
	 */
	function randomDropouts($plID,$players,$gameID,$gameUUID) {
		$dropoutsAvailable = NULL;
		$availablePlayers = array();

		foreach($players as $player) {
			if($_SESSION['playersData']['playerId_'.$player]['dropoutsAvailable'] > 0) {
				$dropoutsAvailable = true;
				$dropoutPlayer = $player;
			} else {
				array_push($availablePlayers, $player);
				$random = array_rand($availablePlayers);
			}
		}
		if(isset($dropoutsAvailable) && ($plID == $dropoutPlayer)) {
			echo "<br /><span class='dropout' data-gameid='".$gameID."' data-playerid='".$availablePlayers[$random]."' onclick='writeForDrops(this)'>zuf. Aussetzen?</span>";
		}
	}

	/**
	 * Logic to skip the player during game.
	 * @access public
	 * @param integer $gameID
	 * @param integer $gameUUID
	 * @param integer $currentPlayerID
	 * @param array $players
	 * @return
	 * @author Harlecino
	 */
	function handleDropouts($gameID,$gameUUID,$currentPlayerID,$players) {
		$currentRound = getCurrentRound($gameID,$gameUUID,$players);
		$dartsCount = getDartsRoundCount($gameUUID,$currentRound,$currentPlayerID);
		if ($_SESSION['playersData']['playerId_'.$currentPlayerID]['dropoutsReceivedInUse'] > 0) {
			if($dartsCount == 2) {
				--$_SESSION['playersData']['playerId_'.$currentPlayerID]['dropoutsReceivedInUse'];
			}
			processScoreScream($gameID,$gameUUID,$score = "0",$scoreMultiplier = "1",$players,$withDrops = 1);
		}
	}

	/**
	 * Spread the dropouts ​​to the opponents.
	 * @access public
	 * @param integer $plID
	 * @param integer $gameID
	 * @param integer $gameUUID
	 * @param integer $currentPlayerID
	 * @param array $players
	 * @return
	 * @author Harlecino
	 */
	function spreadDropouts($plID,$gameID,$gameUUID,$currentPlayerID,$players) {
		// give dropout to player with ID $plID
		$_SESSION['playersData']['playerId_'.$plID]['dropoutsReceivedInUse']++;
		$_SESSION['playersData']['playerId_'.$plID]['dropoutsReceivedTotal']++;

		foreach ($_SESSION['playersData'] as $player => $value) {
			if ($value['dropoutsAvailable'] > 0) {
				--$_SESSION['playersData'][$player]['dropoutsAvailable'];
			}
		}
		if($plID == $currentPlayerID) {
			handleDropouts($gameID,$gameUUID,$currentPlayerID,$players);
		}
	}

	/**
	 * Logic to reset the dropouts after the first arrow is set for the next player.
	 * @access public
	 * @param integer $currentPlayerID
	 * @param array $players
	 * @param integer $gameID
	 * @param integer $gameUUID
	 * @param integer $currentRound
	 * @param integer $becauseDropping
	 * @return
	 * @author Harlecino
	 */
	function resetDropouts($currentPlayerID,$players,$gameID,$gameUUID,$currentRound,$becauseDropping) {
		$dartsRoundCount = getDartsRoundCount($gameUUID,$currentRound,$currentPlayerID);

		if($becauseDropping == 0){
			foreach($players as $player) {
				if(($player != $currentPlayerID) && ($dartsRoundCount != 0)) {
					$_SESSION['playersData']['playerId_'.$player]['dropoutsAvailable'] = 0;
				}
			}
		}
	}
	function processScoreHalfIt($gameID,$gameUUID,$score,$scoreMultiplier,$players) {
		global $mysqli;

		$currentInCondition = getCurrentInCondition($gameID);
		$currentOutCondition = getCurrentOutCondition($gameID);
		$gameStartPoints = getGameStartPoints($gameID);
		$gameTargetPoints = getGameTargetPoints($gameID);
		$currentRound = getCurrentRound($gameID,$gameUUID,$players);

		$currentPlayerID = getCurrentPlayer($gameID,$gameUUID,$currentRound,$players);

		$dartsCount = getDartsRoundCount($gameUUID,$currentRound,$currentPlayerID);
		if ($dartsCount == 3) {
			$currentRound+=1;
			$dartsCount = 0;
		}

		// save score
		if ($score !=null && $scoreMultiplier != null) {
			$halfit = getHalftItPlayerData($gameUUID,$currentPlayerID);
			$multiplier = $halfit->multiplier[$currentRound-1];
			$target = $halfit->targets[$currentRound-1];
			$roundScore = getRoundScore($gameUUID,$currentRound,$currentPlayerID);
			$currentPlayerRestPoints = getCurrentPlayerRestPoints($gameID,$gameUUID,$currentPlayerID);
			if($dartsCount == 2 && $roundScore == 0 && $score != $target) {
				insertScore($gameID,$gameUUID,-($currentPlayerRestPoints/2),1,$currentPlayerID,$currentRound,$dartsCount);
			} else {
				if($score == $target && $scoreMultiplier == $multiplier || ($multiplier == 1 && $score == $target)) {
					insertScore($gameID,$gameUUID,$score,$scoreMultiplier,$currentPlayerID,$currentRound,$dartsCount);
				} else {
					insertScore($gameID,$gameUUID,0,0,$currentPlayerID,$currentRound,$dartsCount);
				}
			}
		}

		$currentPlayerPoints = getCurrentPlayerPoints($gameID,$gameUUID,$currentPlayerID);

		$currentPlayerID = getCurrentPlayer($gameID,$gameUUID,$currentRound,$players);

		$dartsCount = getDartsRoundCount($gameUUID,$currentRound,$currentPlayerID);

		if ($dartsCount == 3) {
			$dartsCount=0;
		}

		printStatisticsHalfIt($gameID,$gameUUID,$currentPlayerID,$players);

	}
	function getHalftItPlayerData($gameUUID,$currentPlayerID) {
		$gameData = getGameData($gameUUID);
		foreach($gameData as $halfitPlayer) {
			if($halfitPlayer->playerID == $currentPlayerID) {
				return $halfitPlayer;
				exit;
			}
		}
	}
	function getCurrentPlayer($gameID,$gameUUID,$currentRound,$players) {
		$playerCount = count($players);
		if ($currentRound == 0) {
			$currentPlayerID = $players[0];
		} else {
			$firstPlayer = $players[0];
			foreach($players as $plID) {
				if(checkPlayerWin($gameID,$gameUUID,$plID,$currentRound)){
					continue;
				}
				$firstPlayer = $plID;
				break;
			}
			for ($i=0; $i<count($players); $i++) {
				$currentPlayerID = $players[$i];
				$count = getDartsRoundCount($gameUUID,$currentRound,$currentPlayerID);
				if(checkPlayerWin($gameID,$gameUUID,$currentPlayerID,$currentRound)){
					if ($i<$playerCount-1) {
						continue;
					} else{
						return $firstPlayer;
					}
				} else {
					if ($count < 3) {
						return $currentPlayerID;
					} else {
						if ($i<$playerCount-1) {
							continue;
						} else {
							return $firstPlayer;
						}
					}
				}
			}
		}
		return $currentPlayerID;
	}
	function printStatisticsX01($gameID,$gameUUID,$currentPlayerID,$players) {
		$currentRound = getCurrentRound($gameID,$gameUUID,$players);
		$dartsRoundCount = getDartsRoundCount($gameUUID,$currentRound,$currentPlayerID);
		echo "<table id='gameheader'>";
		echo "<tr>";
		echo "<td>".getCurrentGameGroup($gameID)."</td>";
		echo "<td>".getCurrentGameName($gameID)."</td>";
		echo "<td>".getCurrentInCondition($gameID)."</td>";
		echo "<td>".getCurrentOutCondition($gameID)."</td>";
		$maxRounds = getCurrentGameMaxRounds($gameID);
		if ($currentRound > $maxRounds) {
			echo "<td>Spiel Ende</td>";
		} else if ($maxRounds == $currentRound) {
			echo "<td><span class='blink red'>Runde ".$currentRound."/".$maxRounds."</span></td>";
		} else {
			echo "<td>Runde ".$currentRound."/".$maxRounds."</td>";
		}

		echo "<td>Dart ".$dartsRoundCount."/3</td>";
		echo "<td>".getAllDartsCount()."</td>";
		echo "</tr>";
		echo "</table>";

		echo "<form id='playersForm'>";
		echo "<table id='scoretable'>";
		$gameFinished = false;
		foreach($players as $plID) {
			if (checkPlayerWin($gameID,$gameUUID,$plID,$currentRound)) {
				$win = "win";
				$gameFinished = true;
			} else {
				$win = "";
				$gameFinished = false;
			}

			echo "<tr>";
			if ($plID == $currentPlayerID) {
				$class = "currentPlayer ".$win;
			} else {
				$class = "player ".$win;
			}
			if(getCurrentGameGroup($gameID) == 'Scream') {
				if ($_SESSION['playersData']['playerId_'.$plID]['dropoutsReceivedInUse'] != "0") {
					$class = $class."dropout";
				}
			}
			echo "<td class='$class digi playerName'>".getPlayerRank($gameUUID,$gameID,$players,$plID);printSaveGameForm($gameUUID,$gameID,$players,$plID);echo "</td>";
			echo "<td class='$class width300 digi playerName'>".getPlayerFirstname($plID)."</td>";
			echo "<td class='$class width180 digi score'>";
			if(getCurrentGameGroup($gameID) == 'Scream' && (getCurrentPlayerRestPoints($gameID,$gameUUID,$plID) == 111 ||getCurrentPlayerRestPoints($gameID,$gameUUID,$plID) == 222)) {
				echo "<span class='red blink'>".getCurrentPlayerRestPoints($gameID,$gameUUID,$plID)."</span>";
			 } else {
				echo getCurrentPlayerRestPoints($gameID,$gameUUID,$plID);
			}
			if(getCurrentGameGroup($gameID) == 'Scream') {
				randomDropouts($plID,$players,$gameID,$gameUUID);
				offerDropouts($plID,$players,$gameID,$gameUUID)."</td>";
			}
			echo "</td>";
			if(getCurrentGameGroup($gameID) == 'Scream') {
				echo "<td class='$class width180 digi scream'>";
				echo ($_SESSION['playersData']['playerId_'.$plID]['lostCounts'] > 0) ? "Genullt: ".$_SESSION['playersData']['playerId_'.$plID]['zero']."<br />" : "";
				echo ($_SESSION['playersData']['playerId_'.$plID]['lostCounts'] > 0) ? "Punkte: ".$_SESSION['playersData']['playerId_'.$plID]['lostCounts']."<br />" : "";
				echo ($_SESSION['playersData']['playerId_'.$plID]['dropoutsReceivedInUse'] > 0) ? "Aussetzen: ".$_SESSION['playersData']['playerId_'.$plID]['dropoutsReceivedInUse']."<br />"  : "";
				echo ($_SESSION['playersData']['playerId_'.$plID]['dropoutsReceivedTotal'] > 0) ? "Ausgesetzt: ".$_SESSION['playersData']['playerId_'.$plID]['dropoutsReceivedTotal'] : "";
				echo "</td>";
			} else {
				echo "<td class='$class width180 digi scoreAvg'>".getCurrentPlayerAvg($gameID,$gameUUID,$plID,$currentRound)."</td>";
			}
			if(getCurrentGameGroup($gameID) == 'Count Up') {
				if(getCurrentGameName($gameID) == '301 U&D') {
					echo "<td class='$class width270 digi scoreAvg'>";
					if($currentRound % 2 != 0) {
						echo "Up";
					} else {
						echo "Down";
					}
				}
			} else if(getCurrentGameGroup($gameID) == 'Scream') {
				echo "<td class='$class width270 digi scream'>";
				if($currentPlayerID == $plID) {
					foreach($players as $playerID) {
						if($playerID != $plID) {
							$restPlSub = getCurrentPlayerRestPoints($gameID,$gameUUID,$playerID);
							$restPl = getCurrentPlayerRestPoints($gameID,$gameUUID,$plID);
							if ($restPl < $restPlSub) {
								$playerName = getPlayerFirstname($playerID);
								echo $playerName." > ".intval($restPlSub-$restPl)."<br/>";
							}
						}
					}
					$playerPoints = getCurrentPlayerRestPoints($gameID,$gameUUID,$plID);
					if ($playerPoints < 111) {
						echo "111 > ".intval(111-$playerPoints)."<br/>";
					} else if ($playerPoints < 222) {
						echo "222 > ".intval(222-$playerPoints)."<br/>";
					}
				}
			} else {
				echo "<td class='$class width270 digi score statistic'>";
				getGameScoreStatistic($gameUUID,$plID,$class);
				echo "<div class='checkout'>".getRoundScoreByDart($gameUUID,$currentRound,$plID)."</div>";
				echo "<div class='checkout'>".getCheckout(getCurrentPlayerRestPoints($gameID,$gameUUID,$plID))."</div></td>";
			}
			echo "</tr>";
		}
		echo "</table>";

		if($_GET['request'] != 'livedartscoreboard' && $_GET['request'] != 'gamedetails2') {
			echo "<input type='hidden' name='game_id' value='".getCurrentOldGameID($gameID)."'>";
			echo "<input type='hidden' name='game_uuid' value='".$gameUUID."'>";
			echo "<input type='submit' name='saveGameScoreBoard' value='Spiel Speichern'/>";
			exit;
		}
		echo "</form>";
	}

	function printStatisticsHalfIt($gameID,$gameUUID,$currentPlayerID,$players) {
		$currentRound = getCurrentRound($gameID,$gameUUID,$players);
		echo "<table id='gameheader'>";
		echo "<tr>";
		echo "<td>".getCurrentGameGroup($gameID)."</td>";
		echo "<td>".getCurrentGameName($gameID)."</td>";
		echo "<td>".getCurrentInCondition($gameID)."</td>";
		echo "<td>".getCurrentOutCondition($gameID)."</td>";
		$maxRounds = getCurrentGameMaxRounds($gameID);
		if ($currentRound > $maxRounds) {
			echo "<td>Spiel Ende</td>";
		} else if ($maxRounds == $currentRound) {
			echo "<td><span class='blink red'>Runde ".$currentRound."/".$maxRounds."</span></td>";
		} else {
			echo "<td>Runde ".$currentRound."/".$maxRounds."</td>";
		}

		echo "<td>Dart ".getDartsRoundCount($gameUUID,$currentRound,$currentPlayerID)."/3</td>";
		echo "<td>".getAllDartsCount()."</td>";
		echo "</tr>";
		echo "</table>";

		echo "<form id='playersForm'>";
		echo "<table id='scoretable'>";
		$gameFinished = false;
		foreach($players as $plID) {
			$halfit = getHalftItPlayerData($gameUUID,$plID);
			if (checkPlayerWin($gameID,$gameUUID,$plID,$currentRound)) {
				$win = "win";
				$gameFinished = true;
			} else {
				$win = "";
				$gameFinished = false;
			}

			echo "<tr>";
			if ($plID == $currentPlayerID) {
				$class = "currentPlayer ".$win;
			} else {
				$class = "player ".$win;
			}
			echo "<td class='$class digi playerName'>".getPlayerRank($gameUUID,$gameID,$players,$plID);printSaveGameForm($gameUUID,$gameID,$players,$plID);echo "</td>";
			echo "<td class='$class width300 digi playerName'>".getPlayerFirstname($plID)."</td>";
			echo "<td class='$class width180 digi score'>".getCurrentPlayerRestPoints($gameID,$gameUUID,$plID)."</td>";
			if($halfit->multiplier[$currentRound-1]!=1) {
				echo "<td class='$class width180 digi scoreAvg'>".$halfit->multiplier[$currentRound-1]." x ".$halfit->targets[$currentRound-1]."</td>";
			} else {
				echo "<td class='$class width180 digi scoreAvg'>".$halfit->targets[$currentRound-1]."</td>";
			}
			echo "<td class='$class width270 digi score statistic'></div></td>";
			echo "</tr>";
		}
		echo "</table>";

		if($_GET['request'] != 'livedartscoreboard' && $_GET['request'] != 'gamedetails2') {
			echo "<input type='hidden' name='game_id' value='".getCurrentOldGameID($gameID)."'>";
			echo "<input type='hidden' name='game_uuid' value='".$gameUUID."'>";
			echo "<input type='submit' name='saveGameScoreBoard' value='Spiel Speichern'/>";
			exit;
		}
		echo "</form>";
	}

	function printSaveGameForm($gameUUID,$gameID,$players,$plID) {
		$rank = getPlayerRank($gameUUID,$gameID,$players,$plID);
		if($_GET['request'] != 'livedartscoreboard' && $_GET['request'] != 'gamedetails2') {
			echo "<div><select name='player_" . $plID . "' size='1'>";
			$points = count($players);
			for ($i = 0; $i < $points; $i++) {
				if($points-$rank==$i) {
					echo "<option selected value='" . $i . "'>" . $i . "</option>";
				} else {
					echo "<option value='" . $i . "'>" . $i . "</option>";
				}
			}
			echo "</select></div>";
		}
	}
	function getPlayerRank($gameUUID,$gameID,$players,$currentPlayer) {
		$gameGroup = getCurrentGameGroup($gameID);
		$playersRank = array();
		foreach(array_reverse($players) as $plID) {
			if ($gameGroup == 'Half It' || $gameGroup == 'Count Up' || $gameGroup == 'Scream') {
				$playersRank[$plID] = getCurrentPlayerPoints($gameID,$gameUUID,$plID);
			} else{
				$playersRank[$plID] = getCurrentPlayerRestPoints($gameID,$gameUUID,$plID);
			}
		}
		if ($gameGroup == 'Half It' || $gameGroup == 'Count Up' || $gameGroup == 'Scream') {
			arsort($playersRank);
		} else {
			asort($playersRank);
		}

		$i=1;
		foreach ($playersRank as $key => $val) {
			if($key == $currentPlayer) {
				return $i;
			}
			$i+=1;
		}
	}
	function checkPlayerWin($gameID,$gameUUID,$currentPlayerID,$currentRound) {
		if (getCurrentGameMaxRounds($gameID) == $currentRound-1)
		{
			return true;
		}
		$targetPoints = getGameTargetPoints($gameID);
		$currentPlayerPoints = getCurrentPlayerRestPoints($gameID,$gameUUID,$currentPlayerID);
		if(getGameGroup($gameID) == 'Count Up') {
			if ($currentPlayerPoints >= $targetPoints) {
				return true;
			} else {
				return false;
			}
		} else {
			if ($currentPlayerPoints == $targetPoints) {
				return true;
			} else {
				return false;
			}
		}
	}
	function insertScore($gameID,$gameUUID,$score,$scoreMultiplier,$currentPlayerID,$currentRound,$currentDart) {
		global $mysqli;
		$sql = "insert into game_score_v2 (game_id,game_uuid,player_id,round,dart,score,score_multiplier) VALUES($gameID, $gameUUID, $currentPlayerID, $currentRound, $currentDart, $score, $scoreMultiplier)";
		mysqli_query($mysqli, $sql);
        $mysqli->commit();
	}
	function getPlayerFirstName($currentPlayerID) {
		global $mysqli;
		$sql = "select contraction from players where id = ".$currentPlayerID;
		$firstName = $mysqli->query($sql)->fetch_object()->contraction;
		if ($firstName == null) {
			$sql = "select firstName from players where id = ".$currentPlayerID;
			$firstName = $mysqli->query($sql)->fetch_object()->firstName;
		}
		return $firstName;
	}
	function getPlayerLastName($currentPlayerID) {
		global $mysqli;
		$sql = "select lastName from players where id = ".$currentPlayerID;
		return $mysqli->query($sql)->fetch_object()->lastName;
	}
	function getCurrentGameGroup($gameID) {
		global $mysqli;
		$sql = "select gameGroup gamegroup from games_v2 where id = ".$gameID;
		$gamegroup = $mysqli->query($sql)->fetch_object()->gamegroup;
		return $gamegroup;
	}
	function getCurrentGameMaxRounds($gameID) {
		global $mysqli;
		$sql = "select maxRounds from games_v2 where id = ".$gameID;
		$maxRounds = $mysqli->query($sql)->fetch_object()->maxRounds;
		return $maxRounds;
	}
	function getCurrentInCondition($gameID) {
		global $mysqli;
		$sql = "select inCondition incondition from games_v2 where id = ".$gameID;
		$incondition = $mysqli->query($sql)->fetch_object()->incondition;
		if($incondition == 'Single') $incondition = 'SI';
		if($incondition == 'Double') $incondition = 'DI';
		if($incondition == 'Master') $incondition = 'MI';
		return $incondition;
	}
	function getCurrentOutCondition($gameID) {
		global $mysqli;
		$sql = "select outCondition outcondition from games_v2 where id = ".$gameID;
		$outcondition = $mysqli->query($sql)->fetch_object()->outcondition;
		if($outcondition == 'Single') $outcondition = 'SO';
		if($outcondition == 'Double') $outcondition = 'DO';
		if($outcondition == 'Master') $outcondition = 'MO';
		return $outcondition;
	}
	function getCurrentGameName($gameID) {
		global $mysqli;
		$sql = "select name from games_v2 where id = ".$gameID;
		$name = $mysqli->query($sql)->fetch_object()->name;
		return $name;
	}
	function getCurrentOldGameID($gameID) {
		global $mysqli;
		$sql = "select id from games where idNew = ".$gameID;
		$id = $mysqli->query($sql)->fetch_object()->id;
		return $id;
	}
	function getNewGameID($gameID) {
		global $mysqli;
		$sql = "select idNew from games where id = ".$gameID;
		$idNew = $mysqli->query($sql)->fetch_object()->idNew;
		return $idNew;
	}
	function getCurrentRound($gameID,$gameUUID,$players) {
		global $mysqli;
		$sql = "select max(round) round from game_score_v2 where game_uuid = ".$gameUUID;
		$round = $mysqli->query($sql)->fetch_object()->round;
		if($round == 0)
		{
			return 1;
		}

		$sql = "select count(round) dartscount from game_score_v2 where game_uuid = ".$gameUUID;
		$dartscount = $mysqli->query($sql)->fetch_object()->dartscount;
		if($dartscount/3/count($players)/$round == 1)
		{
			$round = $round + 1;
		}
		return $round;
	}
	function getCurrentPlayerDartsGameCount($gameUUID,$currentPlayerID) {
		global $mysqli;
		$sql = "select count(*) dartscount from game_score_v2 where player_id = ".$currentPlayerID." and game_uuid = ".$gameUUID;
		$dartsCount = $mysqli->query($sql)->fetch_object()->dartscount;
		if($dartsCount == null) $dartsCount = 1;
		return $dartsCount;
	}
	function getDartsRoundCount($gameUUID,$currentRound,$currentPlayerID) {
		global $mysqli;
		$sql = "select count(*) dartscount from game_score_v2 where player_id = ".$currentPlayerID." and game_uuid = ".$gameUUID." and round = ".$currentRound;
		$dartsCount = $mysqli->query($sql)->fetch_object()->dartscount;
		if($dartsCount == null) $dartsCount = 1;
		return $dartsCount;
	}
	function getRoundScore($gameUUID,$currentRound,$currentPlayerID) {
		global $mysqli;
		$sql = "select sum(score*score_multiplier) points from game_score_v2 where player_id = ".$currentPlayerID." and game_uuid = ".$gameUUID." and round = ".$currentRound;
		$roundScore = $mysqli->query($sql)->fetch_object()->points;
		if($roundScore == null) $roundScore = 0;
		return $roundScore;
	}
	function getRoundScoreByDart($gameUUID,$currentRound,$currentPlayerID) {
		global $mysqli;
		$sql = "select score,score_multiplier from game_score_v2 where player_id = ".$currentPlayerID." and game_uuid = ".$gameUUID." and round = ".$currentRound;
		$res = $mysqli->query($sql);
		$ret ="";
		while ($row = $res->fetch_assoc()) {
			if($row['score_multiplier'] !=1 && $row['score_multiplier'] !=0) {
				$ret=$ret.$row['score_multiplier']."x".$row['score']." ";
			} else {
				if($row['score'] > 0) {
					$ret=$ret.$row['score']." ";
				}
			}
		}
		return $ret;
	}
	function getCurrentPlayerRestPoints($gameID,$gameUUID,$currentPlayerID) {
		global $mysqli;
		$sql = "select sum(score*score_multiplier) points from game_score_v2 where player_id = ".$currentPlayerID." and game_uuid = ".$gameUUID;
		$currentPlayerPoints = $mysqli->query($sql)->fetch_object()->points;
		if($currentPlayerPoints == null) {
			$currentPlayerPoints = getGameStartPoints($gameID);
		} else {
			if(getGameGroup($gameID) == 'Count Up' || getGameGroup($gameID) == 'Half It' || getGameGroup($gameID) == 'Scream') {
				$currentPlayerPoints = getGameStartPoints($gameID) + $currentPlayerPoints;
			} else {
				$currentPlayerPoints = getGameStartPoints($gameID) - $currentPlayerPoints;
			}
		}
		return $currentPlayerPoints;
	}
	function getCurrentPlayerPoints($gameID,$gameUUID,$currentPlayerID) {
		global $mysqli;
		$sql = "select sum(score*score_multiplier) points from game_score_v2 where player_id = ".$currentPlayerID." and game_uuid = ".$gameUUID;
		$currentPlayerPoints = $mysqli->query($sql)->fetch_object()->points;
		if($currentPlayerPoints == null) {
			$currentPlayerPoints = getGameStartPoints($gameID);
		}
		return $currentPlayerPoints;
	}
	function getCurrentPlayerAvg($gameID,$gameUUID,$currentPlayerID,$currentRound) {
		$currentPlayerPoints = getCurrentPlayerPoints($gameID,$gameUUID,$currentPlayerID);
		$currentPlayerDartsGameCount = getCurrentPlayerDartsGameCount($gameUUID,$currentPlayerID);
		if ($currentPlayerPoints == 0) {
			return 0;
		} else {
			if($currentPlayerDartsGameCount<3) {
				return 0;
			} else {
				return round($currentPlayerPoints/($currentPlayerDartsGameCount/3));
			}
		}
	}
	function getAllDartsCount() {
		global $mysqli;
		$sql = "select count(*) count from game_score_v2";
		$count = $mysqli->query($sql)->fetch_object()->count;
		return $count;
	}
	function getGameScoreStatistic($gameUUID,$currentPlayerID,$class) {
		global $mysqli;
		if($gameUUID == null && $currentPlayerID == null) {
			$sql = "select score*score_multiplier score,count(score*score_multiplier) scorecount from game_score_v2 where score >= 0 group by score,score_multiplier order by scorecount desc";
		} else if($currentPlayerID != null) {
			$sql = "select score*score_multiplier score,count(score*score_multiplier) scorecount from game_score_v2 where score >= 0 and game_uuid = ".$gameUUID." and player_id = ".$currentPlayerID." group by score,score_multiplier order by scorecount desc";
		} else {
			$sql = "select score*score_multiplier score,count(score*score_multiplier) scorecount from game_score_v2 where score >= 0 and game_uuid = ".$gameUUID." group by score,score_multiplier order by scorecount desc";
		}
		$res = $mysqli->query($sql);
		echo "<table id='scorestatistics'>";
		echo "<tr>";
		while ($row = $res->fetch_assoc()) {
			echo "<td class='".$class."'>".$row['score']."</td>";
		}
		echo "</tr>";
		echo "<tr>";
		$res = $mysqli->query($sql);
		while ($row = $res->fetch_assoc()) {
			echo "<td class='".$class."'>".$row['scorecount']."</td>";
		}
		echo "</tr>";
		echo "</table>";
	}
	function getGameStartPoints($gameID) {
		global $mysqli;
		$sql = "select startPoints startpoints from games_v2 where id = ".$gameID;
		$startpoints = $mysqli->query($sql)->fetch_object()->startpoints;
		return $startpoints;
	}
	function getGameTargetPoints($gameID) {
		global $mysqli;
		$sql = "select targetPoints targetpoints from games_v2 where id = ".$gameID;
		$targetpoints = $mysqli->query($sql)->fetch_object()->targetpoints;
		return $targetpoints;
	}

	function printSQLResult($sql) {
		global $mysqli;
		$res = $mysqli->query($sql);
		while ($row = $res->fetch_assoc()) {
			foreach($row as $cname => $cvalue){
				print "$cname: $cvalue\t";
			}
			print "<br/>";
		}
	}

	$gameGroup = null;
	$name = null;
	$inCondition = null;
	$outCondition = null;
	$gameID	= null;

	if(isset($_GET['gameGroup'])) {
		$gameGroup = $_GET['gameGroup'];
	}
	if(isset($_GET['name'])) {
		$name = $_GET['name'];
	}
	if(isset($_GET['inCondition'])) {
		$inCondition = $_GET['inCondition'];
	}
	if(isset($_GET['outCondition'])) {
		$outCondition = $_GET['outCondition'];
	}

	if(count($_GET) > 0) {
		//getForm($mysqli,$gameGroup,$name,$inCondition,$outCondition);
		exit;
	}

	function printDartScoreBoard($gameID,$gameUUID,$players) {
		?>
			<html>
			<head>
				<title>ScoreBoard</title>
				<script type="text/javascript" src="scripts/jquery-2.1.0.min.js"></script>
				<script type="text/javascript" src="scripts/jquery-ui.js"></script>
				<script type="text/javascript" src="scripts/main.js"></script>
				<script type="text/javascript" src="scripts/dartautomat.js"></script>
				<script type="text/javascript" src="scripts/jquery.contextMenu.js"></script>
				<script type="text/javascript" src="scripts/jquery.hoverIntent.minified.js"></script>
				<script type="text/javascript" src="scripts/jquery.windowmsg-1.0.js"></script>
				<script type="text/javascript" src="scripts/jquery.iosslider.js"></script>
				<link rel="stylesheet" type="text/css" href="css/dartautomat.css"/>
				<script type='text/javascript'>
					jQuery(document).ready(function() {
						jQuery.initWindowMsg();
						jQuery.windowMsg("dartboardMsg", function(data) {
							$.ajax({
								url: "dartautomat.php",
								type: "GET",
								data: JSON.parse(data),
								success: function(data) {
									jQuery("#dartscoreboard").html(data);
								}
							});
						});
					});
				</script>
			</head>
			<body>
				<div id="dartscoreboard">
					<?php
					$gameGroup = getGameGroup($gameID);

					processGame($gameGroup,$gameID,$gameUUID,$players,null,null);
					?>
				</div>
			</body>
		</html>
		<?php
	}

	function printDartBoard($gameID,$gameUUID,$players) {
		?>
		<html>
			<head>
				<title>DartBoard</title>
				<script type="text/javascript" src="scripts/jquery-2.1.0.min.js"></script>
				<script type="text/javascript" src="scripts/jquery-ui.js"></script>
				<script type="text/javascript" src="scripts/jquery.windowmsg-1.0.js"></script>
				<script type="text/javascript" src="scripts/dartautomat.js"></script>
				<script type="text/javascript" src="scripts/jquery.iosslider.js"></script>
				<link rel="stylesheet" type="text/css" href="css/dartautomat.css"/>

				<script type='text/javascript'>
					jQuery(document).ready(function() {
						init();
						initMousePointer();
					});
				</script>
			</head>
			<body>

				<div id="dartautomat">
					<div id="dartomat" class="dartomat">
						<canvas id="dartcanvas" data-game-id="<?php print($gameID) ?>" data-game-uuid="<?php print($gameUUID) ?>">Your browser does not support HTML5</canvas>
					</div>
				</div>

				<form id='undo' action='<?=$_SERVER['PHP_SELF']?>' method='POST'>
					<input name='request' type='hidden' value='undo'/>
					<input name='game_uuid' type='hidden' value='<?=$gameUUID?>'/>
					<input name='game_id' type='hidden' value='<?=$gameID?>'/>
					<input name='buttonUndo' type='submit' value='Zur&uuml;ck'/>
					<?php
					$players = $_GET['playerid'];
					foreach($players as $player) {
					?>
						<input name='playerid[]' type='hidden' value='<?=$player?>'/>
					<?php
					}
					?>
				</form>
				<div id='scores'></div>
			</body>
		</html>

		<?php
	}

	function getCheckout($score) {
	$checkouts = array (
	170=>"T20-T20-Bull",133=>"T20-T11-D20",96=>"T20-D18",
	169=>"kein Finish",132=>"T20-T12-D18",95=>"T19-D19",
	168=>"kein Finish",131=>"T20-T17-D10",94=>"T18-D20",
	167=>"T20-T19-Bull",130=>"T20-S20-Bull",93=>"T19-D18",
	166=>"kein Finish",129=>"T19-T12-D18",92=>"T20-D16",
	165=>"kein Finish",128=>"T18-T14-D16",91=>"T17-D20",
	164=>"T20-T18-Bull",127=>"T20-T17-D8",90=>"T18-D18",
	163=>"kein Finish",126=>"T19-S19-Bull",89=>"T19-D16",
	162=>"kein Finish",125=>"25-T20-D20",88=>"T16-D20",
	161=>"T20-T17-Bull",124=>"T20-S14-Bull",87=>"T17-D18",
	160=>"T20-T20-D20",123=>"T19-T10-D18",86=>"T18-D16",
	159=>"kein Finish",122=>"T18-T12-D16",85=>"T15-D20",
	158=>"T20-T20-D19",121=>"T20-T7-D20",84=>"T20-D12",
	157=>"T20-T19-D20",120=>"T20-S20-D20",83=>"T17-D16",
	156=>"T20-T20-D18",119=>"T20-S19-D20",82=>"T14-D20",
	155=>"T20-T19-D19",118=>"T20-S18-D20",81=>"T15-D18",
	154=>"T20-T18-D20",117=>"T20-S17-D20",80=>"T20-D10",
	153=>"T20-T19-D18",116=>"T20-S16-D20",79=>"T13-D20",
	152=>"T20-T20-D16",115=>"T20-S15-D20",78=>"T18-D12",
	151=>"T20-T17-D20",114=>"T20-S14-D20",77=>"T19-D10",
	150=>"T20-T18-D18",113=>"T20-S13-D20",76=>"T20-D8",
	149=>"T20-T19-D16",112=>"T20-S20-D16",75=>"T17-D12",
	148=>"T20-T16-D20",111=>"T20-S19-D16",74=>"T18-D10",
	147=>"T19-T18-D18",110=>"T20-S18-D16",73=>"T19-D8",
	146=>"T20-T18-D16",109=>"T20-S17-D16",72=>"T12-D18",
	145=>"T20-T15-D20",108=>"T20-S16-D16",71=>"T17-D10",
	144=>"T18-T18-D18",107=>"T19-Bull",70=>"T10-D20",
	143=>"T20-T17-D16",106=>"T20-S10-D18",69=>"T13-D15",
	142=>"T20-T14-D20",105=>"T20-S13-D16",68=>"T20-D4",
	141=>"T17-T18-D18",104=>"T18-Bull",67=>"T17-D8",
	140=>"T20-T20-D10",103=>"T20-S3-D20",66=>"T10-D18",
	139=>"T19-T14-D20",102=>"T20-S10-D16",65=>"25-D20",
	138=>"T20-T18-D12",101=>"T17-Bull",64=>"T16-D8",
	137=>"T19-T20-D10",100=>"T20-D20",63=>"T13-D12",
	136=>"T20-T20-D8",99=>"T20-S7-D16",62=>"T10-D16",
	135=>"T17-T20-D12",98=>"T20-D19",61=>"25-D18",
	134=>"T20-T14-D16",97=>"T19-D20",60=>"S20-D20");
	if ($score >= 60 && $score <=170) {
		return $checkouts[$score];
	}
}
?>